<template>
  <div class="settings-page">
    <el-row :gutter="20">
      <el-col :span="6">
        <!-- 设置菜单 -->
        <div class="card">
          <el-menu
            :default-active="activeTab"
            @select="handleMenuSelect"
            class="settings-menu"
          >
            <el-menu-item index="profile">
              <el-icon><User /></el-icon>
              <span>个人信息</span>
            </el-menu-item>
            <el-menu-item index="security">
              <el-icon><Lock /></el-icon>
              <span>安全设置</span>
            </el-menu-item>
            <el-menu-item index="notification">
              <el-icon><Bell /></el-icon>
              <span>通知设置</span>
            </el-menu-item>
            <el-menu-item index="system">
              <el-icon><Setting /></el-icon>
              <span>系统设置</span>
            </el-menu-item>
            <el-menu-item index="organization">
              <el-icon><OfficeBuilding /></el-icon>
              <span>组织架构</span>
            </el-menu-item>
          </el-menu>
        </div>
      </el-col>

      <el-col :span="18">
        <!-- 个人信息 -->
        <div v-show="activeTab === 'profile'" class="card">
          <h3>个人信息</h3>
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="100px"
            style="max-width: 600px"
          >
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                :action="uploadAction"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="profileForm.username" disabled />
            </el-form-item>
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="profileForm.realName" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="profileForm.phone" />
            </el-form-item>
            <el-form-item label="部门" prop="department">
              <el-input v-model="profileForm.department" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdateProfile">保存修改</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 安全设置 -->
        <div v-show="activeTab === 'security'" class="card">
          <h3>安全设置</h3>
          <div class="security-section">
            <div class="security-item">
              <div class="security-info">
                <h4>登录密码</h4>
                <p>定期更换密码可以提高账户安全性</p>
              </div>
              <el-button @click="showPasswordDialog = true">修改密码</el-button>
            </div>
            <div class="security-item">
              <div class="security-info">
                <h4>两步验证</h4>
                <p>开启两步验证后，登录时需要输入手机验证码</p>
              </div>
              <el-switch v-model="securitySettings.twoFactorAuth" />
            </div>
            <div class="security-item">
              <div class="security-info">
                <h4>登录通知</h4>
                <p>账户登录时发送邮件通知</p>
              </div>
              <el-switch v-model="securitySettings.loginNotification" />
            </div>
          </div>
        </div>

        <!-- 通知设置 -->
        <div v-show="activeTab === 'notification'" class="card">
          <h3>通知设置</h3>
          <el-form label-width="150px">
            <el-form-item label="邮件通知">
              <el-checkbox-group v-model="notificationSettings.email">
                <el-checkbox label="case_update">案件状态更新</el-checkbox>
                <el-checkbox label="contract_expire">合同即将到期</el-checkbox>
                <el-checkbox label="new_message">新消息提醒</el-checkbox>
                <el-checkbox label="system_notice">系统公告</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="短信通知">
              <el-checkbox-group v-model="notificationSettings.sms">
                <el-checkbox label="urgent_case">紧急案件</el-checkbox>
                <el-checkbox label="court_reminder">开庭提醒</el-checkbox>
                <el-checkbox label="deadline_warning">截止日期警告</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="系统通知">
              <el-checkbox-group v-model="notificationSettings.system">
                <el-checkbox label="browser_notification">浏览器通知</el-checkbox>
                <el-checkbox label="sound_alert">声音提醒</el-checkbox>
                <el-checkbox label="desktop_notification">桌面通知</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdateNotification">保存设置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 系统设置 -->
        <div v-show="activeTab === 'system'" class="card">
          <h3>系统设置</h3>
          <el-form label-width="150px">
            <el-form-item label="系统主题">
              <el-radio-group v-model="systemSettings.theme">
                <el-radio label="light">浅色主题</el-radio>
                <el-radio label="dark">深色主题</el-radio>
                <el-radio label="auto">跟随系统</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="语言设置">
              <el-select v-model="systemSettings.language" style="width: 200px">
                <el-option label="简体中文" value="zh-CN" />
                <el-option label="English" value="en-US" />
              </el-select>
            </el-form-item>
            <el-form-item label="时区设置">
              <el-select v-model="systemSettings.timezone" style="width: 200px">
                <el-option label="北京时间 (UTC+8)" value="Asia/Shanghai" />
                <el-option label="纽约时间 (UTC-5)" value="America/New_York" />
                <el-option label="伦敦时间 (UTC+0)" value="Europe/London" />
              </el-select>
            </el-form-item>
            <el-form-item label="自动保存">
              <el-switch v-model="systemSettings.autoSave" />
              <span style="margin-left: 10px; color: #909399;">自动保存表单数据</span>
            </el-form-item>
            <el-form-item label="数据备份">
              <el-switch v-model="systemSettings.autoBackup" />
              <span style="margin-left: 10px; color: #909399;">每日自动备份数据</span>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdateSystem">保存设置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 组织架构 -->
        <div v-show="activeTab === 'organization'" class="card">
          <h3>组织架构</h3>
          <div class="org-toolbar">
            <el-button type="primary" @click="handleAddDepartment">
              <el-icon><Plus /></el-icon>
              添加部门
            </el-button>
          </div>
          <el-tree
            :data="organizationData"
            :props="{ children: 'children', label: 'name' }"
            show-checkbox
            node-key="id"
            class="org-tree"
          >
            <template #default="{ node, data }">
              <span class="org-node">
                <span>{{ data.name }}</span>
                <span class="org-actions">
                  <el-button type="text" size="small" @click="handleEditDepartment(data)">编辑</el-button>
                  <el-button type="text" size="small" @click="handleDeleteDepartment(data)">删除</el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>
    </el-row>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="400px">
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input v-model="passwordForm.currentPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { updateUser } from '@/api/user'

const userStore = useUserStore()
const activeTab = ref('profile')
const showPasswordDialog = ref(false)
const profileFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

// 上传配置
const uploadAction = computed(() => '/api/upload/avatar')
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${userStore.token}`
}))

// 个人信息表单
const profileForm = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  department: '',
  avatar: ''
})

const profileRules: FormRules = {
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

// 密码修改表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules: FormRules = {
  currentPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 安全设置
const securitySettings = reactive({
  twoFactorAuth: false,
  loginNotification: true
})

// 通知设置
const notificationSettings = reactive({
  email: ['case_update', 'system_notice'],
  sms: ['urgent_case'],
  system: ['browser_notification']
})

// 系统设置
const systemSettings = reactive({
  theme: 'light',
  language: 'zh-CN',
  timezone: 'Asia/Shanghai',
  autoSave: true,
  autoBackup: true
})

// 组织架构数据
const organizationData = ref([
  {
    id: 1,
    name: '总经理办公室',
    children: []
  },
  {
    id: 2,
    name: '法务部',
    children: [
      { id: 21, name: '诉讼组' },
      { id: 22, name: '合规组' },
      { id: 23, name: '知识产权组' }
    ]
  },
  {
    id: 3,
    name: '行政部',
    children: [
      { id: 31, name: '人事组' },
      { id: 32, name: '财务组' }
    ]
  }
])

// 菜单选择
const handleMenuSelect = (index: string) => {
  activeTab.value = index
}

// 头像上传前检查
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像上传成功
const handleAvatarSuccess = (response: any) => {
  profileForm.avatar = response.url
  ElMessage.success('头像上传成功')
}

// 更新个人信息
const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return
  
  try {
    await profileFormRef.value.validate()
    await updateUser(userStore.userInfo!.id, profileForm)
    ElMessage.success('个人信息更新成功')
    userStore.getUserInfo()
  } catch (error: any) {
    ElMessage.error(error.message || '更新失败')
  }
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    // TODO: 调用修改密码API
    ElMessage.success('密码修改成功')
    showPasswordDialog.value = false
    passwordForm.currentPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  } catch (error: any) {
    ElMessage.error(error.message || '密码修改失败')
  }
}

// 更新通知设置
const handleUpdateNotification = () => {
  ElMessage.success('通知设置已保存')
}

// 更新系统设置
const handleUpdateSystem = () => {
  ElMessage.success('系统设置已保存')
}

// 添加部门
const handleAddDepartment = () => {
  ElMessage.info('添加部门功能开发中')
}

// 编辑部门
const handleEditDepartment = (data: any) => {
  ElMessage.info('编辑部门功能开发中')
}

// 删除部门
const handleDeleteDepartment = (data: any) => {
  ElMessage.info('删除部门功能开发中')
}

onMounted(() => {
  // 初始化个人信息
  if (userStore.userInfo) {
    Object.assign(profileForm, userStore.userInfo)
  }
})
</script>

<style lang="scss" scoped>
.settings-page {
  .settings-menu {
    border: none;
    
    .el-menu-item {
      border-radius: 8px;
      margin-bottom: 4px;
      
      &.is-active {
        background: #409eff;
        color: #fff;
      }
    }
  }
  
  .security-section {
    .security-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .security-info {
        h4 {
          margin: 0 0 8px 0;
          font-size: 16px;
          font-weight: 500;
        }
        
        p {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
      }
    }
  }
  
  .org-toolbar {
    margin-bottom: 20px;
  }
  
  .org-tree {
    .org-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      
      .org-actions {
        opacity: 0;
        transition: opacity 0.3s;
      }
      
      &:hover .org-actions {
        opacity: 1;
      }
    }
  }
  
  .avatar-uploader {
    .avatar {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      object-fit: cover;
    }
    
    .avatar-uploader-icon {
      width: 100px;
      height: 100px;
      border: 2px dashed #d9d9d9;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: #8c939d;
      cursor: pointer;
      
      &:hover {
        border-color: #409eff;
        color: #409eff;
      }
    }
  }
}
</style>
